from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
from rest_framework import serializers
from .models import *
from mutils import SMSCode
from rest_framework.viewsets import ModelViewSet
import re
from rest_framework.exceptions import ValidationError
# class Usersers(serializers.ModelSerializer):
#     class Meta:
#         model=User
#         fields=['username','password']

class Codeser(serializers.Serializer):
    phone=serializers.CharField(max_length=11)

    def validate_phone(self,phone):
        if not re.match('^1[3578]\d{9}$',phone):
            raise ValidationError('手机格式错误')
        return phone

class Userser(serializers.ModelSerializer):
    code=serializers.CharField(max_length=6,write_only=True)
    class Meta:
        model=User
        fields=['username','password','code','phone']

    def validate(self, attrs):
        code=attrs.get('code')
        phone=attrs.get('phone')
        obj=Code.objects.filter(phone=phone).order_by('-time').first()
        if not obj:
            raise ValidationError('没有向该手机发送验证码')
        if code!=obj.code:
            raise ValidationError('验证码有误')
        return attrs

    def create(self, validated_data):
        del validated_data['code']
        return User.objects.create_user(**validated_data)

class CodeAPIView(APIView):
    def post(self,request):
        ser=Codeser(data=request.data)
        ser.is_valid(raise_exception=True)
        phone=ser.validated_data.get('phone')
        sms=SMSCode()
        yzm=sms.send(phone)
        code=sms.code
        if yzm['status']==0:
            Code.objects.create(phone=phone,code=code)
            return Response({'验证码':code,'验证码状态':yzm['msg']})
        return Response({'验证码状态':yzm['msg']})

class RegisterView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = Userser

class Denglu(APIView):
    def get(self,request):
        # username=request.data.get('username')
        # password=request.data.get('password')
        user=Userser(data=request.data)
        user.is_valid(raise_exception=True)
        username=user.validated_data.get('username')
        password=user.validated_data.get('password')
        obj=User.objects.filter(username=username,password=password).first()
        if not obj:
            raise ValidationError('账号或者密码有误')
        ser=Userser(instance=obj)
        return Response(ser.data)
